
// GhostMod 0.1 by Brennan Underwood
// brennan@winamp.com

#include "../../lib/std.mi"

Global Timer fader, active_checker;
Global int prev_active = -1;

Function adjustLayout(Layout l);	// sets desktopalpha mode
Function int fadeto(Container c, Layout l, int targetalpha);

#define ACTIVEALPHA 230
#define INACTIVEALPHA 150

adjustLayout(Layout l) {
  l.setDesktopAlpha(true);
}

System.onScriptLoaded() {
  prev_active = -1;
  active_checker = new Timer;
  active_checker.setDelay(200);
  active_checker.start();
  fader = new Timer;
  fader.setDelay(50);
  // don't start it yet

  int n = getNumContainers();
  for (int i = 0; i < n; i++) {
    Container c = enumContainer(i);
    int nl = c.getNumLayouts();
    for (int j = 0; j < nl; j++) {
      Layout l = c.enumLayout(j);
      adjustLayout(l);
    }
  }
}

System.onCreateLayout(Layout l) {
  adjustLayout(l);
}

System.onScriptUnloading() {
  delete active_checker;
  delete fader;
}

active_checker.onTimer() {
  if (fader.isRunning()) return;	// already fading
  // start up fader if state changed
  int isactive = isAppActive();
  if (isactive != prev_active) {
    prev_active = isactive;
    fader.start();
  }
}

int fadeto(Container c, Layout l, int targetalpha) {
  if (c.getId() == "Component") return 0;
  int mal = l.getAlpha();
  if (mal == targetalpha) {
    return 0;	// didn't need to adjust it
  }
  if (mal > targetalpha) {
    mal = mal - 2;
    if (mal < targetalpha) mal = targetalpha;
  } else if (mal < targetalpha) {
    mal = mal + 8;
    if (mal > targetalpha) mal = targetalpha;
  }
  l.setAlpha(mal);
  return 1;
}

fader.onTimer() {
  int isactive = isAppActive();
  int targetalpha = ACTIVEALPHA;
  if (!isactive) targetalpha = INACTIVEALPHA;

  int done = 1;

  int n = getNumContainers();
  for (int i = 0; i < n; i++) {
    Container c = enumContainer(i);
    int nl = c.getNumLayouts();
    for (int j = 0; j < nl; j++) {
      Layout l = c.enumLayout(j);
      done *= !fadeto(l, targetalpha);
    }
  }
  if (done) fader.stop();
}
